<template>
  <view class="container">
    <!-- 顶部图片 -->
    <image v-if="topImgUrl" class="top-img" :src="topImgUrl"></image>
    <view v-else class="top-img-placeholder"><image style="width: 100%;" src="../../static/top.jpg"></image></view>

    <!-- 标签栏 -->
    <view class="tab-bar">
      <view 
        :class="['tab-item', currentTab === 'ongoing' ? 'active-tab' : '']" 
        @click="currentTab = 'ongoing'"
      >
        进行中
      </view>
      <view 
        :class="['tab-item', currentTab === 'ended' ? 'active-tab' : '']" 
        @click="currentTab = 'ended'"
      >
        已结束
      </view>
    </view>

    <!-- 内容列表 -->
    <view class="content-list">
      <block v-if="currentTab === 'ongoing'">
        <view class="item" v-for="(item, index) in ongoingList" :key="item.activityId || index">
          <view class="item-img-container">
			  
            <!-- <image v-if="item.activityImg" class="item-img" :src="item.activityImg"></image> -->
            <view class="img-placeholder"><image style="height: 100%;" src="/static/1.png"></image></view>
          </view>
          <view class="item-info">
            <view class="item-title">{{item.activityName}}</view>
            <!-- <view class="item-organizer">{{item.organizer}}</view> -->
            <view style="margin-top: 13px;" class="item-joined">已报名{{ item.enrollment || 0 }}人</view>
            
            <!-- 培训信息 -->
            <!-- <view class="training-info">
              <view class="info-row">
                <uni-icons type="location" size="14"></uni-icons>
                <text>{{ formatAddress(item) }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="calendar" size="14"></uni-icons>
                <text>{{ formatDate(item.trainingInfo.startDate) }} 至 {{ formatDate(item.trainingInfo.endDate) }}</text>
              </view>
            </view> -->
            
            <!-- 学习进度 -->
            <view class="study-progress-container">
              <view class="study-info">
                <view class="study-text">线上学习进度</view>
                <view class="study-detail">
                  <view class="time-info">
                    <view>总时长: {{ item.totalMinutes }}分钟</view>
                    <view>已学习: {{ calculateProgress(item).learnedMinutes }}分钟</view>
                  </view>
                  <view class="progress-bar">
                    <view class="progress" :style="{ width: calculateProgress(item).percent + '%' }"></view>
                  </view>
                </view>
              </view>
              
              <button style="margin-left: 16px;" class="go-study" @click="goStudy(item)">
                {{ calculateProgress(item).percent === 0 ? '开始学习' : '继续学习' }}
              </button>
            </view>
            
            <view class="progress-text">进度：{{ calculateProgress(item).percent }}%</view>
          </view>
        </view>
      </block>

      <!-- 已结束活动列表 -->
      <block v-else>
        <view class="item" v-for="(item, index) in endedList" :key="item.activityId || index">
          <!-- 结构与进行中活动类似，只是按钮状态不同 -->
          <button class="go-end" disabled>已结束</button>
        </view>
      </block>

      <view v-if="ongoingList.length === 0 && currentTab === 'ongoing'" class="no-more">
        暂无进行中的活动
      </view>
      <view v-if="endedList.length === 0 && currentTab === 'ended'" class="no-more">
        暂无已结束的活动
      </view>
    </view>
<!-- 	<view class="bottom-tabbar">
	  <view class="tabbar-item" @click="goHome">
	    <uni-icons type="home" size="24"></uni-icons>
	    <view>首页</view>
	  </view>
	  <view class="tabbar-item" @click="goStudyRecord">
	    <uni-icons type="wallet-filled" size="24"></uni-icons>
	    <view>学习记录</view>
	  </view>
	  <view class="tabbar-item" @click="goMy">
	    <uni-icons type="auth" size="24"></uni-icons>
	    <view>我的</view>
	  </view>
	</view> -->
  </view>
</template>
<script>
import { getAllActivity, getActivityList } from '/api/activity.js';

export default {
  data() {
    return {
      currentTab: 'ongoing',
      ongoingList: [],
      endedList: [],
      topImgUrl: '',
      isLoading: false,
      errorMsg: '',
      userId: ''
    };
  },
  async onLoad() {
    try {
      // 获取用户ID
      this.userId = uni.getStorageSync('userInfo').userId;
      // 获取进行中的活动
      const res = await getAllActivity(0, this.userId);

      // 处理返回的数据
      if (res.code == '200') {
        // 处理Proxy对象并解析JSON字符串字段
        const rawData = JSON.parse(JSON.stringify(res.data));
        this.ongoingList = this.formatActivityData(rawData);
        console.log('处理后的活动数据:', this.ongoingList);
      } else {
        uni.showToast({ title: res.message || '获取活动失败', icon: 'none' });
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      uni.showToast({ title: '获取活动失败，请重试', icon: 'none' });
    }
  },
  methods: {
    // 格式化活动数据，解析JSON字符串字段
    formatActivityData(data) {
      if (!data) return [];
      
      // 如果数据是Proxy对象或数组形式
      const activities = Array.isArray(data) ? data : Object.values(data);
      
      return activities.map(item => {
        // 解析trainingInfo
        try {
          item.trainingInfo = item.trainingInfo ? JSON.parse(item.trainingInfo) : [];
          if (item.trainingInfo.length > 0) {
            item.trainingInfo = item.trainingInfo[0]; // 取第一个培训信息
          }
        } catch (e) {
          item.trainingInfo = {};
        }
        
        // 解析videosInfo
        try {
          item.videosInfo = item.videosInfo ? JSON.parse(item.videosInfo) : [];
        } catch (e) {
          item.videosInfo = [];
        }
        
        // 计算总学习时长(分钟)
        item.totalMinutes = Math.floor((item.videosLength || 0) / 60);
        
        return item;
      });
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未设置';
      return dateString.split(' ')[0];
    },
    
    // 格式化地址信息
    formatAddress(item) {
      if (item.trainingInfo && item.trainingInfo.address) {
        return item.trainingInfo.address;
      }
      return '未设置培训地点';
    },
    
    // 计算学习进度
	calculateProgress(item) {
	  // 从item中获取用户已学习时长（需后端返回）
	  const learnedMinutes = item.learnedMinutes || 0;
	  const totalMinutes = Number(item.totalMinutes) || 0;
	  const progress = totalMinutes > 0 ? Math.min(100, Math.round((learnedMinutes / totalMinutes) * 100)) : 0;
	  return { percent: progress, learnedMinutes };
	},
    
	goStudy(item) {
	  // 从 item.videosInfo 中取第一个 videoId（根据实际结构调整）
	  const videoId = item.videosInfo.length > 0 ? item.videosInfo[0].videoId : ''; 
	  uni.navigateTo({
		url: `/pages/study/study?activityId=${item.activityId}&videoId=${videoId}`
	  });
	},
    goHome() {
      uni.switchTab({ url: '/pages/main/main' });
    },
    
    goStudyRecord() {
      uni.navigateTo({ url: '/pages/record/record' });
    },
    
    goMy() {
      uni.switchTab({ url: '/pages/my/my' });
    }
  }
};
</script>
<style scoped>
/* 顶部图片样式 */
.top-img {
  width: 100%;
  height: 200px;
}

.top-img-placeholder {
  width: 100%;
  height: 200px;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}

/* 活动图片容器样式 */
.item-img-container {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.item-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.img-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

/* 标签栏样式 */
.tab-bar {
  display: flex;
  border-bottom: 1px solid #f2f2f2;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  color: #333;
}

.active-tab {
  color: #ff5722;
  border-bottom: 2px solid #ff5722;
}

/* 内容列表样式 */
.content-list {
  flex: 1;
  padding: 10px;
}

.item {
  display: flex;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #f2f2f2;
  border-radius: 8px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.item-joined {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

/* 学习进度容器样式 */
.study-progress-container {
  padding: 0;
  margin: 0;
  display: flex;
  align-items: flex-end;
  margin-bottom: 5px;
}

.study-info {
  padding: 0;
  margin: 0;
  flex: 1;
}

.study-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.study-detail {
  font-size: 12px;
  color: #999;
}

.time-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2px;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: #f2f2f2;
  border-radius: 3px;
}

.progress {
  height: 6px;
  background-color: #ff5722;
  border-radius: 3px;
}

.progress-text {
  font-size: 12px;
  color: #ff5722;
  text-align: right;
}

/* 按钮样式 */
.go-study {
  white-space: nowrap;
  padding: 5px 12px;
  background-color: #ff5722;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  border: none;
}

.go-end {
  white-space: nowrap;
  padding: 5px 12px;
  background-color: #a5a09d;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  border: none;
}

/* 暂无更多提示样式 */
.no-more {
  text-align: center;
  color: #999;
  padding: 10px 0;
}

/* 底部导航样式 */
.bottom-tabbar {
  display: flex;
  border-top: 1px solid #f2f2f2;
}

.tabbar-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #333;
}
</style>